
import type { IReqSingleResource,IReqCreateUser,IReqLoginUser, IRspApi } from "@packages/shared"

/** 可访问的资源名称 */
export const CONST_Resource = {
    User: 'User',
    Dict: 'Dict',
} as const

export type OnSuccess = (<T>(data: T) => void) | undefined
export type OnBusinessError = ((msg: string) => void) | undefined
export type OnError = (<T>(data: T) => void) | undefined

export type HttpConfig<T> = {
    param: T
    onSuccess?: OnSuccess
    onBusinessError?: OnBusinessError
    onError?: OnError
}

/** 
 * ### 请求适配器 
 * 
 * 可根据需要自定义适配器，如：axios、fetch、uni.request等
 * 
 * 默认提供了简易的 fetch 适配器，也可以实现自己的请求适配器
 * 
 */
export type RequestAdapter = <T>(url: string, options: RequestInit) => Promise<{ json(): Promise<T> }>;


export const http = async <T>(
  baseUrl: string,
  method: string,
  config: HttpConfig<T>,
  adapter: RequestAdapter = fetch  // 默认使用 fetch
) => {
  try {
    const result = await adapter(baseUrl + '/' + method, {
      method: 'POST',
      body: JSON.stringify(config.param),
      headers: {
        'Content-Type': 'application/json'
      }
    });

    const res = (await result.json()) as IRspApi;
    if (res.code === 200)
      config.onSuccess && config.onSuccess(res.data);
    else
      config.onBusinessError && config.onBusinessError(res.msg);
  } catch (error) {
    config.onError && config.onError(error);
  }
};

export const baseUrl = 'http://localhost:3000/api/rpc/v1'

export const const_API = {
    singleResource: (config: HttpConfig<IReqSingleResource>, adapter?: RequestAdapter) => http(baseUrl, 'singleResource', config, adapter),
    registerNewUser: (config: HttpConfig<IReqCreateUser>, adapter?: RequestAdapter) => http(baseUrl, 'registerNewUser', config, adapter),
    loginUser: (config: HttpConfig<IReqLoginUser>, adapter?: RequestAdapter) => http(baseUrl, 'loginUser', config, adapter),
} as const

    